<template>
  <view>
    <view class="interface">
      <text class="corner-text top-left" style="font-size: 35rpx">设备</text>
      <text
        class="corner-text top-right"
        v-if="!connectionStatus"
        @click="initBlue"
        >搜索设备并连接</text
      >
      <text class="corner-text top-right" v-else @click="disConnectd"
        >点击断开连接</text
      >
      <!-- <image src="../../static/images/blood_oxygen.png"></image> -->
      <text class="corner-text bottom-left"
        >指压式脉搏血氧仪\n <text style="color: #808080">A0J-30B</text></text
      >
      <text
        class="corner-text bottom-right"
        style="font-size: 50rpx; font-weight: bolder"
      >
        ·<text
          style="color: black; font-size: 30rpx; font-weight: normal"
          v-if="!connectionStatus"
        >
          未连接</text
        >
        <text
          v-else
          style="color: black; font-size: 30rpx; font-weight: normal"
        >
          已连接</text
        >
      </text>
    </view>
    <uni-popup ref="popup" :mask-click="true" @close="handlePopupClose">
      <device-connection
        :device-name="deviceName"
        @send="connetionCallBack"
        ref="deviceConnection"
      >
      </device-connection>
      <!-- <button @click="close">关闭</button> -->
    </uni-popup>

    <view v-for="(item, index) in presureInfoList" :key="index">
      <view class="data-card">
        <view class="header">
          <text style="color: #48c454">| 正常血压</text>
          <text style="color: #808080; margin-left: 10rpx"
            >{{item.createdAt}}</text
          >
        </view>
        <view class="pressure">
          <view class="vvv">
            <text style="font-size: 48rpx; color: black; font-weight: bolder"
              >{{item.highPresureValue}}</text
            >
            <text style="font-size: 12px; color: #808080">高压</text>
          </view>
          <view class="vertical-line"></view>
          <view class="vvv">
            <text style="font-size: 48rpx; color: black; font-weight: bolder"
              >{{item.lowPresureVale}}</text
            >
            <text style="font-size: 12px; color: #808080">低压</text>
          </view>
          <view class="vertical-line"></view>
          <view class="vvv">
            <text style="font-size: 48rpx; color: black; font-weight: bolder"
              >{{item.heartRate}}</text
            >
            <text style="font-size: 12px; color: #808080">心率</text>
          </view>
        </view>
      </view>
    </view>
    <view>
      <button @click="open">点击开始测量</button>
      <uni-popup ref="popup1" type="dialog" :is-mask-click="true">
        <pop-up-card
          :pressure-value="valueList[valueList.length - 1]"
        ></pop-up-card>
        <button @click="close" style="margin-top: 800rpx">关闭</button>
      </uni-popup>
    </view>
    <view v-if="testOver">
      <testover
        :highValue="highValue[highValue.length - 1]"
        :lowValue="lowValue[lowValue.length - 1]"
        :pulseRate="pulseRate[pulseRate.length - 1]"
      ></testover>
      <button @click="closeResult">点击关闭</button>
    </view>
  </view>
</template>

<script>
import { postPresureInfo, getPresureInfo } from "../../api/presure";
export default {
  created() {
    this.getMyPresureInfos();
		this.presureInfo.userId = this.$store.state.user.currId
		console.log(this.presureInfo)
  },
  data() {
    return {
      presureInfoList: [],
      presureInfo: {
        heartRate: 0,
        highPresureValue: 0,
        lowPresureVale: 0,
        normal: 0,
        userId: this.$store.state.user.currId,
      },
      deviceName: "血压仪器",
      highValue: [], // 高压
      lowValue: [], // 低压
      pulseRate: [], // 脉率
      connectionStatus: false,
      testOver: false,
      bluetoothDevices: [], // 存储蓝牙设备列表
      serviceId: "",
      notifyId: "",
      deviceId: "", // 0xFFE0，0xFFE1 0xFFE2
      valueList: [], // 这里的话要对第三个数除10
    };
  },
  methods: {
    getMyPresureInfos() {
      getPresureInfo(this.$store.state.user.currId)
        .then((res) => {
          this.presureInfoList = res;
					console.log(this.presureInfoList)
          console.log("get presure successfully");
        })
        .catch((err) => {
          console.log("currId:" + this.$store.state.user.currId);
          console.log("get presure failed");
          console.log(err);
        });
    },
    postPresure() {
      if (this.$store.state.user.currId != 0) {
        postPresureInfo(this.presureInfo)
          .then((res) => {
            this.getMyPresureInfos();
          })
          .catch((err) => {
            console.log("post presure falied");
            console.log(err);
            console.log(this.presureInfo);
          });
      }
    },
    mockTest() {
      let value = 60;
      let i = 0;
      const delayedLoop = () => {
        if (i < 20) {
          setTimeout(() => {
            console.log(i);
            if (i <= 10) {
              value += 10;
              this.valueList.push(value);
            } else {
              value -= 10;
              this.valueList.push(value);
            }
            i++;
            delayedLoop(); // 递归调用 delayedLoop 函数
          }, 1000); // 每次迭代延迟 3000 毫秒执行
        } else {
          console.log("test over");
          this.testOver = true;
          this.highValue.push(78);
          this.lowValue.push(78);
          this.pulseRate.push(80);
          this.close();
        }
      };
      delayedLoop(); // 启动递归函数
    },
    closeResult() {
      this.testOver = false;
      this.postPresure();
    },
    open() {
      this.$refs.popup1.open(); // 调用弹窗组件的 open 方法
      this.getCharacteristics()
      // this.mockTest();
    },
    close() {
      this.$refs.popup1.close(); // 调用弹窗组件的 close 方法
    },
    connetionCallBack(deviceId, serviceId) {
      this.deviceId = deviceId;
      this.serviceId = serviceId;
      console.log("Received deviceId:", deviceId);
      console.log("Received serviceUuid:", serviceId);
      this.connectionStatus = true;
    },
    handlePopupClose() {
      this.$refs.popup.close();
      this.stopBluetoothDiscovery();
    },
    disConnectd() {
      this.connectionStatus = false;
      this.closeConnection();
    },
    initBlue() {
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log("初始化蓝牙成功");
          console.log(res);
          this.$refs.popup.open("center");
          this.$refs.deviceConnection.init();
        },
        fail: (err) => {
          console.log("初始化蓝牙失败");
          console.error(err);
        },
      });
    },
    stopBluetoothDiscovery() {
      uni.stopBluetoothDevicesDiscovery({
        success: (res) => {
          console.log("蓝牙搜索已停止", res);
          // this.bluetoothDevices = [];
        },
        fail: (err) => {
          console.error("停止蓝牙搜索失败", err);
        },
      });
    },
    notifyDevice(notifyId) {
      console.log("进入了消息监听，下面是特征值");
      console.log(notifyId);
      console.log("正在进行监听数据");
      uni.notifyBLECharacteristicValueChange({
        state: true,
        deviceId: this.deviceId, // 设备ID，在【4】里获取到
        serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
        characteristicId: notifyId, // 特征值，在【7】里能获取到
        success: (res) => {
          console.log("监听成功");
          console.log(res);
          // 接受消息的方法
          this.listenValueChange();
        },
        fail: (err) => {
          console.log("监听失败，原因如下");
          console.error(err);
        },
      });
    },
    getCharacteristics() {
      uni.getBLEDeviceCharacteristics({
        deviceId: this.deviceId, // 设备ID，在【4】里获取到
        serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
        success: (res) => {
          this.characteristicIdList = res.characteristics;
          for (let i = 0; i < this.characteristicIdList.length; i++) {
            // console.log(this.characteristicIdList[i])
            if (this.characteristicIdList[i].properties.notify) {
              this.characteristicId = this.characteristicIdList[i].uuid;
              this.notifyId = this.characteristicIdList[i].uuid;
              console.log(this.notifyId);
              this.notifyDevice(this.notifyId);
              console.log("获取特征值成功且赋值成功");
              break;
            }
          }
        },
        fail: (err) => {
          console.error("获取特征值失败");
          console.error(err);
        },
      });
    },
    // 检查血压的连接
    check(str) {
      if (str.substring(0, 8) == "d0c204cb") {
        console.log("测量中");
        this.valueList.push(parseInt(str.substring(8, 12)));
      }
      if (str.substring(0, 8) == "d0c20ccc") {
        console.log("测量成功");
        this.testOver = true;
        const arr = this.hexToDecimal(str);
        this.highValue.push(arr[3]);
        this.lowValue.push(arr[4]);
        this.pulseRate.push(arr[5]);
        console.log(arr);
        this.presureInfo.heartRate = arr[5];
        this.presureInfo.highPresureValue = arr[3];
        this.presureInfo.lowPresureVale = arr[4];
        this.close();
      }
    },
    getTime() {
      // 创建一个新的日期对象
      var now = new Date();

      // 获取年份
      var year = now.getFullYear();

      // 获取月份（0-11）
      var month = now.getMonth() + 1;

      // 获取日期
      var date = now.getDate();

      // 获取小时
      var hours = now.getHours();

      // 获取分钟
      var minutes = now.getMinutes();

      // 获取秒钟
      var seconds = now.getSeconds();

      // 格式化输出时间
      var formattedTime =
        year +
        "-" +
        month +
        "-" +
        date +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;

      // 在控制台打印时间
      console.log(formattedTime);
    },
    listenValueChange() {
      console.log("监听中...");
      this.getTime();
      uni.onBLECharacteristicValueChange((res) => {
        // 结果里有个value值，该值为 ArrayBuffer 类型，所以在控制台无法用肉眼观察到，必须将该值转换为16进制
        let resHex = this.ab2hex(res.value);
        // console.log(resHex);
        this.check(resHex);
      });
    },
    closeConnection() {
      console.log("正在断开连接");
      this.getTime();
      uni.closeBLEConnection({
        deviceId: this.deviceId,
        success: (res) => {
          console.log(res);
          console.log("断开连接成功");
        },
        fail: (err) => {
          console.log(err);
          console.log("断开连接失败");
        },
      });
    },
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ("00" + bit.toString(16)).slice(-2);
        }
      );
      return hexArr.join("");
    },
    hexToDecimal(hexString) {
      const decimalList = [];
      for (let i = 2; i < hexString.length; i += 2) {
        const hexValue = hexString.substring(i, i + 2);
        const decimalValue = parseInt(hexValue, 16);
        decimalList.push(decimalValue);
      }
      return decimalList;
    },
  },
};
</script>

<style>
.interface {
  /* position: absolute; */
  flex-wrap: wrap;
  position: absolute;
  width: 85%;
  height: 25%;
  left: 7%;
  top: 28%;
  background: #ffffff;
  box-shadow: 4px 4px 4px #94d6e2;
  border-radius: 15px;
}

.corner-text {
  font-size: 12px;
  position: absolute;
}

.top-left {
  top: 10px;
  left: 10px;
}

.top-right {
  top: 10px;
  right: 10px;
  color: #48c454; /* 绿色文本 */
}

.bottom-left {
  bottom: 10px;
  left: 10px;
}

.bottom-right {
  bottom: 10px;
  right: 10px;
  color: #48c454; /* 绿色文本 */
}

.data-card {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  background-color: #ffffff;
  margin-top: 50%;
}

.pressure {
  display: flex;
  justify-content: center;
  width: 100%;
  flex-direction: row;
  /*   align-items: center; */
}

.vvv {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  margin-right: 40rpx;
  margin-left: 40rpx;
}

.vertical-line {
  height: 80rpx; /* 控制竖线的高度 */
  width: 2px; /* 控制竖线的宽度 */
  background-color: #cccccc;
  margin: 0 20rpx;
}
.label {
  font-size: 12px;
  color: #808080; /* 灰色文本 */
}
</style>

<!-- <style>
	.interface{
	  /* position: absolute; */
	  flex-wrap:wrap;
		position: absolute;
	  width: 315px;
	  height: 136px;
	  left: 30px;
	  top: 148px;
	  background: #FFFFFF;
	  box-shadow: 4px 4px 4px #94D6E2;
	  border-radius: 15px;

  }

  .corner-text {
    font-size: 12px;
    position: absolute;
	
  }
  
  .top-left {
    top: 10px;
    left: 10px;
  }
  
  .top-right {
    top: 10px;
    right: 10px;
    color: #48C454; /* 绿色文本 */
  }
  
  .bottom-left {
    bottom: 10px;
    left: 10px;
  }
  
  .bottom-right {
    bottom: 10px;
    right: 10px;
    color: #48C454; /* 绿色文本 */
  }
  

  .data-card {
  display: flex; 
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100vw;
  background-color: #FFFFFF;
  margin-top: 400rpx;
  }

 .pressure{
    display: flex;
	justify-content: center;
	width: 100%;
	flex-direction: row;
    align-items: center;
  }
  
  .vvv{
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  margin-top: 20rpx;
	  margin-bottom: 20rpx;
	  margin-right: 40rpx;
	  margin-left: 40rpx;
  }
  
  .vertical-line {
    height: 80rpx; /* 控制竖线的高度 */
    width: 2px; /* 控制竖线的宽度 */
    background-color: #CCCCCC;
    margin: 0 20rpx; 
  }
  .label {
    font-size: 12px;
    color: #808080; /* 灰色文本 */
  }
</style> -->
